package cn.zd.demo1;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.annotation.SuppressLint;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.Manifest;

import java.util.ArrayList;
import java.util.List;

import cn.zd.demo1.sql.entity.TblContact;
import cn.zd.demo1.util.ContentProviderUserInfoConstant;
import cn.zd.demo1.util.StringUtil;
import cn.zd.demo1.util.ViewCheckUtil;

import android.provider.ContactsContract;

public class PermissionActivity extends AppCompatActivity implements View.OnClickListener {

    // 权限列表
    // 通讯录
    private static final String[] PERMISSIONS_CONTACTS = new String[]{
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.WRITE_CONTACTS,
    };
    private static final String[] PERMISSIONS_SMS = new String[]{
            Manifest.permission.SEND_SMS,
            Manifest.permission.READ_SMS,
    };
    // 请求权限requestCode
    public static final int REQUEST_CODE_CONTACTS = 1;
    public static final int REQUEST_CODE_SMS = 2;

    private TextView tv_main;

    private EditText et_name;
    private EditText et_phone;
    private EditText et_email;
    private CheckBox ck_trans;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_permission);
        Toast.makeText(this, this.getClass().getName(), Toast.LENGTH_LONG).show();
        findViewById(R.id.btn_openpermissionsetting).setOnClickListener(this);
        findViewById(R.id.btn_checkpermission).setOnClickListener(this);
        findViewById(R.id.btn_req_contacts_permission).setOnClickListener(this);
        findViewById(R.id.btn_req_sms_permission).setOnClickListener(this);
        et_name = findViewById(R.id.et_name);
        et_phone = findViewById(R.id.et_phone);
        et_email = findViewById(R.id.et_email);
        tv_main = findViewById(R.id.tv_main);
        ck_trans = findViewById(R.id.ck_trans);
        findViewById(R.id.btn_contact_save).setOnClickListener(this);
        findViewById(R.id.btn_contact_read).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_openpermissionsetting) {
            // 打开权限设置
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.fromParts("package", getPackageName(), null));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Toast.makeText(this, "即将打开权限设置", Toast.LENGTH_LONG).show();
            startActivity(intent);
        } else if (v.getId() == R.id.btn_checkpermission) {
            // 检查权限 6.0之后才需要
            StringBuffer sb = new StringBuffer("权限检查结果：");
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                sb.append("\n").append("通讯录读取：").append(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED ? "允许" : "不允许")
                        .append("\n").append("通讯录写入：").append(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED ? "允许" : "不允许")
                        .append("\n").append("短信读取：").append(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED ? "允许" : "不允许")
                        .append("\n").append("短信发送：").append(ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED ? "允许" : "不允许");
                tv_main.setText(sb.toString());
            }
        } else if (v.getId() == R.id.btn_req_contacts_permission) {
            // 请求权限
            List<String> reqpermission = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_DENIED) {
                Toast.makeText(this, "通讯录读取权限不足", Toast.LENGTH_LONG).show();
                reqpermission.add(Manifest.permission.READ_CONTACTS);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_DENIED) {
                Toast.makeText(this, "通讯录写入权限不足", Toast.LENGTH_LONG).show();
                reqpermission.add(Manifest.permission.WRITE_CONTACTS);
            }
            if (reqpermission.size() > 0) {
                Toast.makeText(this, "即将弹出授权窗口", Toast.LENGTH_LONG).show();
                ActivityCompat.requestPermissions(this, reqpermission.toArray(new String[reqpermission.size()]), REQUEST_CODE_CONTACTS);
            } else {
                Toast.makeText(this, "已有权限，无需反复授权", Toast.LENGTH_LONG).show();
            }
        } else if (v.getId() == R.id.btn_req_sms_permission) {
            // 请求权限
            List<String> reqpermission = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_DENIED) {
                Toast.makeText(this, "短信读取权限不足", Toast.LENGTH_LONG).show();
                reqpermission.add(Manifest.permission.READ_SMS);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_DENIED) {
                Toast.makeText(this, "发送短信权限不足", Toast.LENGTH_LONG).show();
                reqpermission.add(Manifest.permission.SEND_SMS);
            }
            if (reqpermission.size() > 0) {
                Toast.makeText(this, "即将弹出授权窗口", Toast.LENGTH_LONG).show();
                ActivityCompat.requestPermissions(this, reqpermission.toArray(new String[reqpermission.size()]), REQUEST_CODE_SMS);
            } else {
                Toast.makeText(this, "已有权限，无需反复授权", Toast.LENGTH_LONG).show();
            }
        } else if (v.getId() == R.id.btn_contact_save) {
            // 保存到通讯录
            // 检查权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_DENIED) {
                Toast.makeText(this, "请先授权", Toast.LENGTH_SHORT).show();
                return;
            }
            // 参数检查
            if (!ViewCheckUtil.checkEditText(et_name)) {
                Toast.makeText(this, "请填写姓名", Toast.LENGTH_SHORT).show();
                et_name.requestFocus();
                return;
            }
            if (!ViewCheckUtil.checkEditText(et_phone)) {
                Toast.makeText(this, "请填写电话", Toast.LENGTH_SHORT).show();
                et_name.requestFocus();
                return;
            }
            if (!ViewCheckUtil.checkEditText(et_email)) {
                Toast.makeText(this, "请填写邮箱", Toast.LENGTH_SHORT).show();
                et_name.requestFocus();
                return;
            }
            if (ck_trans.isChecked()) {
                // 事务
                saveContactsWithTrans();
            } else {
                // 无事务
                try {
                    saveContacts();
                } catch (Exception e) {
                    Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        }else if(v.getId() == R.id.btn_contact_read) {
            List<TblContact> contacts = new ArrayList<>();
            ContentResolver resolver = getContentResolver();
            Cursor query = resolver.query(ContactsContract.RawContacts.CONTENT_URI, new String[]{ContactsContract.RawContacts._ID}, null, null);
            while (query.moveToNext()) {
                TblContact contact = new TblContact();
                int rawContactId = query.getInt(0);
                 Uri uri = Uri.parse("content://com.android.contacts/contacts/"+rawContactId+"/data");
                Cursor query_1 = resolver.query(uri, new String[]{ContactsContract.Contacts.Data.MIMETYPE, ContactsContract.Contacts.Data.DATA1, ContactsContract.Contacts.Data.DATA2}, null, null);
                while (query_1.moveToNext()) {
                    @SuppressLint("Range") String data1 = query_1.getString(query_1.getColumnIndex(ContactsContract.Contacts.Data.DATA1));
                    @SuppressLint("Range") String mimeType = query_1.getString(query_1.getColumnIndex(ContactsContract.Contacts.Data.MIMETYPE));
                    switch (mimeType) {
                        case ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE:
                            contact.setName(data1);
                            break;
                        case ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE:
                            contact.setPhone(data1);
                            break;
                        case ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE:
                            contact.setEmail(data1);
                            break;
                    }
                }
                query_1.close();
                if(contact.getName() == null) {
                    Log.i("获取通讯录", "空的id:"+rawContactId);
                }else {
                    contacts.add(contact);
                }
            }
            query.close();
            tv_main.setText("获取所有联系人： "+StringUtil.listToString(contacts));
        }
    }

    private void saveContactsWithTrans() {
        // 主表
        ContentProviderOperation op_main = ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI).withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build();
        // 姓名
        ContentProviderOperation op_name = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Contacts.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Contacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.Contacts.Data.DATA2, et_name.getText().toString())
                .build();
        // 电话
        ContentProviderOperation op_phone = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Contacts.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Contacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.Contacts.Data.DATA1, et_phone.getText().toString())
                .withValue(ContactsContract.Contacts.Data.DATA2, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
                .build();
        // 邮箱
        ContentProviderOperation op_email = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Contacts.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Contacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.Contacts.Data.DATA1, et_email.getText().toString())
                .withValue(ContactsContract.Contacts.Data.DATA2, ContactsContract.CommonDataKinds.Email.TYPE_HOME)
                .build();
        ArrayList<ContentProviderOperation> ops = new ArrayList<>();
        ops.add(op_main);
        ops.add(op_name);
        ops.add(op_phone);
        ops.add(op_email);
        try {
            getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
            Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void saveContacts() {
        TblContact contact = new TblContact(et_name.getText().toString(), et_phone.getText().toString(), et_email.getText().toString());
        // 主表添加记录
        ContentValues values = new ContentValues();
        Uri uri = getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, values);
        // 取到id
        long rawContactId = ContentUris.parseId(uri);

        // 姓名
        // 子表属性添加记录
        values = new ContentValues();
        // 联系人编号
        values.put(ContactsContract.Contacts.Data.RAW_CONTACT_ID, rawContactId);
        // “姓名”类型
        values.put(ContactsContract.Contacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
        // 联系人姓名
        values.put(ContactsContract.Contacts.Data.DATA2, contact.getName());
        // 添加姓名记录
        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);

        // 电话
        // 子表属性添加记录
        values = new ContentValues();
        // 联系人编号
        values.put(ContactsContract.Contacts.Data.RAW_CONTACT_ID, rawContactId);
        // “电话”类型
        values.put(ContactsContract.Contacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
        // 联系人电话
        values.put(ContactsContract.Contacts.Data.DATA1, contact.getPhone());
        values.put(ContactsContract.Contacts.Data.DATA2, ContactsContract.CommonDataKinds.Phone.TYPE_HOME);
        // 添加电话记录
        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);

        // 邮箱
        // 子表属性添加记录
        values = new ContentValues();
        // 联系人编号
        values.put(ContactsContract.Contacts.Data.RAW_CONTACT_ID, rawContactId);
        // “邮箱名”类型
        values.put(ContactsContract.Contacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
        // 联系人邮箱
        values.put(ContactsContract.Contacts.Data.DATA1, contact.getEmail());
        values.put(ContactsContract.Contacts.Data.DATA2, ContactsContract.CommonDataKinds.Email.TYPE_HOME);
        // 添加邮箱记录
        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // permissions权限的清单与grantResults申请结果数组顺序保持一致，可以用于判断多项权限下的具体结果
        switch (requestCode) {
            case REQUEST_CODE_CONTACTS:
                // 通讯录权限
                StringBuffer info = new StringBuffer();
                if (grantResults != null && grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        info.append("通讯录授权：第")
                                .append(i)
                                .append("授权结果：")
                                .append(grantResults[i] == PackageManager.PERMISSION_GRANTED ? "已通过" : "未授权");
                    }
                }
                Toast.makeText(this, "通讯录授权结果回调", Toast.LENGTH_LONG).show();
                tv_main.setText(info.toString());
                break;
            case REQUEST_CODE_SMS:
                // 短信权限
                StringBuffer info1 = new StringBuffer();
                if (grantResults != null && grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        info1.append("短信授权：第")
                                .append(i)
                                .append("授权结果：")
                                .append(grantResults[i] == PackageManager.PERMISSION_GRANTED ? "已通过" : "未授权");
                    }
                }
                Toast.makeText(this, "短信授权结果回调", Toast.LENGTH_LONG).show();
                tv_main.setText(info1.toString());
                break;

        }
    }
}